import React, { useCallback, useEffect, useReducer, useRef, useState } from "react";
import useGame from "@/components/pages/game/car/stores/useGameK";
// import {Container,Sprite,Graphics,Application,AnimatedSprite, Rectangle} from "pixi.js"
import { EndComp, HeaderComp, KRuleComp, ReadyComp } from "@/components/pages/game/car";
import { NotiComp } from "@/components/common";
import classnames from "classnames";
import { isValid, isValidArr, navigateTo } from "@/utils";
import { Button, Modal, Toast } from "antd-mobile";
import { useRouter } from "next/router";
import { v4 } from "uuid";
import { API, BASE_PATH } from "@/config";
import useShare from "@/components/common/hooks/useShare";
import useApp from "@/stores/useApp";
import { signIn, useSession } from "next-auth/react";
import callFeedback from "@/components/common/modalFeedback";
import ModalForm from "./ModalForm";
import requewt from "@/utils/requewt";
import Cookies from "universal-cookie";


const pageName = "game";
const klassName = pageName.replace(/\./g, '-');

export default function GameK() {
  let phase = useGame(state => state.phase)
  let start = useGame(state => state.start)
  const change = useGame(state => state.change)
  const {data} = useSession()
  const { handleAppShareToH5 } = useShare()
  const modalFormRef = useRef()
  // const user = useApp(state => state.user)
  useEffect(() => {
    (async () => {
      // await Toast.show({icon: `loading`, content: `游戏加载中`, duration: 0, maskClickable: false})

      // const app = await loadSource();
      // setCanvas(app);

      // await app.loader.onComplete.add(e => {
      //   // renderGame(app);
      //   Toast.show({content: `加载完成`, duration: 1000})
      // });

      
    })()

    return () => {
      Toast.clear();
    };
  }, [])

  
  useEffect(() => {
    if (phase==='ready') {
      const cookies = new Cookies(document.cookie)
      signIn("credentials", {
        token: cookies.get(`auth`), redirect: false
      });
    }
  }, [phase])
  

  const startGame = () => {
    
  }
  const handler = {
    start: async (id) => {
      start()
      callFeedback({
        bodyClassName: 'act-feedback-modal close-at-center-bottom',
        title: '分享极狐之美',
        hideClose:true,
        actions: <Button className="act-btn act-btn-bevel" onClick={() => {
          // console.log()
          const values = modalFormRef.current.getFormValue()
          const params = {}
          // Object.keys(values).forEach(key => {
          //   if (values[key]) {
          //     params[key] = values[key]
          //   }
          // })
          Toast.show({
            content:'加载中',
            duration:0
          })
          requewt(API.user.userPostInfo, {method:'POST',headers: {'Content-Type':'multipart/form-data'},body:values }).then(({error_code,msg}) => {
            Toast.clear()
            if (error_code === 0) {
              Modal.clear()
              Toast.show('提交成功')

            } else {
              Toast.show({content: <div dangerouslySetInnerHTML={{__html:msg}}></div>})
            }
          }).catch(() => {
            Toast.clear()
          })
        }}>
          提交
        </Button>,
        onClose() {
          change('phase','ready')
        },
        content: <div>
          <ModalForm ref={modalFormRef} />
        </div>
      })
    },
    // switch: () => {
    //   window.location.href = (`/`)
    // },
    visible: (val) => setVisible(val)
  }

  return (
    <>
      <div className={classnames(`p-${klassName} page playing`)}>
        
        {
          phase === `ready` &&
          <ReadyComp handler={handler} type={`k`}>
            <NotiComp>
              <div style={{position:'relative'}}>
                <img 
                  src={`${BASE_PATH}/img/game/game-type-1.png`}
                />
                <Button className="act-btn act-btn-bevel ready-btn" onClick={handler.start} >
                  去完成
                </Button>
              </div>
            </NotiComp>

            <NotiComp>
            <div style={{position:'relative'}}>
            <img 
                  src={`${BASE_PATH}/img/game/game-type-2.png`}
                />
                <div style={{position: 'absolute',
    left: '4px',
    color: '#3f4e66',
    bottom: 0,
    fontSize: '1rem'}}>
                  您今日已成功邀请{data?.user.today_invite_num||0}人
                </div>
                {
                  data?.user.today_invite_num >= 10 ? <div className="ready-btn" style={{color:'#3f4e66',right:0,fontSize:14}} >今日任务已完成</div>:<Button className="act-btn act-btn-bevel ready-btn" onClick={handleAppShareToH5}>
                  去邀请
                </Button>
                }
            </div>
            </NotiComp>
          </ReadyComp>
        }

        

      </div>

      {/* <audio ref={au}
             src={`${BASE_PATH}/audio/ding.mp3`} /> */}
    </>
  )
}

